package com.lyb.spzx.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.lyb.spzx.model.vo.common.Result;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import com.lyb.spzx.pay.properties.AlipayProperties;
import com.lyb.spzx.pay.service.AlipayService;
import com.lyb.spzx.pay.service.PaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/order/alipay")
@Slf4j
public class AlipayController {
    @Autowired
    AlipayService alipayService;

    @Autowired
    PaymentInfoService paymentInfoService;
    @Autowired
    AlipayProperties alipayProperties;

    @Operation(summary="支付宝下单")
    @GetMapping("/submitAlipay/{orderNo}")
    public Result<String> submitAlipay(@PathVariable String orderNo){
        String form = alipayService.submitAlipay(orderNo);
        return Result.build(form, ResultCodeEnum.SUCCESS);
    }

    @Operation(summary = "支付宝异步回调")
    @RequestMapping("/callback/notify")
    public String alipayNotify(@RequestParam Map<String, String> paramMap, HttpServletRequest request) {
        log.info("AlipayController...alipayNotify方法执行了...");
        boolean signVerified; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCertCheckV1(paramMap,alipayProperties.alipayPublicKey
                    ,AlipayProperties.charset
                    ,AlipayProperties.sign_type);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        if (signVerified) {
            String trade_status = paramMap.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)){
                paymentInfoService.updatePaymentStatus(paramMap, 2);
                return "success";
            }else {
                return "failure" ;
            }

        }

        return "failure" ;
    }
}
